package org.rcy.framework.job.registry.consul;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.session.model.NewSession;

public class ConsulDistributedLock {

    private ConsulClient consulClient;

    public ConsulDistributedLock() {

    }

    public String acquireLock(String lockKey) {
        NewSession session = new NewSession();
        session.setName("elasticjob-session");
        String sessionId = consulClient.sessionCreate(session, null).getValue();
        boolean locked = consulClient.setKVValue(lockKey + "_" + sessionId, "true").getValue();
        if (locked) {
            return sessionId;
        }
        return null;
    }

    public void releaseLock(String lockKey, String sessionId) {
        consulClient.sessionDestroy(sessionId, null);
        consulClient.deleteKVValue(lockKey + "_" + sessionId);
    }
}
